<?php

namespace App\Api;


use App\Http\Controllers\Controller;
use App\Http\Resources\UsedResource;
use App\Models\Article;
use App\Models\Used;
use Illuminate\Http\Request;

class UsedController extends Controller
{

    public function index(Article $article)
    {
        $useds = UsedResource::collection($article->useds);
        return $useds;
    }


    public function store(Request $request, Article $article, Used $used)
    {
//        return $request;
        $request->validate([
            'title' => ['required', 'min:3'],
            'content' => ['required', 'min:5'],
            'preview' => ['required']
        ], [
            'preview.required' => '缩略图需上传'
        ]);
        $used = $article->useds()->create($request->input());
        $used->extra = ['price' => $request->price, 'time' => $request->time];

        $used->save();
        return $this->message('发表成功', $used->toArray());
    }

    public function show(Article $article, Used $used)
    {
        return new UsedResource($used);
    }


    public function update(Request $request, Article $article, Used $used)
    {
        $request->validate([
            'title' => ['required', 'min:3'],
            'content' => ['required', 'min:5'],
            'preview' => ['required']
        ], [
            'preview.required' => '缩略图需上传'
        ]);
        $article->useds()->find($used->id)->update($request->input());
//        $used->update($request->input());
        $used->extra = ['price' => $request->price, 'time' => $request->time];

        $used->save();
        return $this->message('修改成功', $used->toArray());
    }


    public function destroy(Article $article, Used $used)
    {
        $used->delete();
        return $this->message('删除成功');
    }

    /**
     * 首页接口
     * @return Used[]|\Illuminate\Database\Eloquent\Collection
     */
    public function usedList()
    {
        return Used::where('recommend', 1)->orderBy('id', 'desc')->take(6)->get();
    }
}
